package com.ctsi.djcloudmqtt.util.secure;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;

import java.io.UnsupportedEncodingException;

public class DESUtil {

    private static final String DES_KEY_SEED = "@#…………&￥#…………&&￥##";
    private static final String DES_KEY = "1c16cc87a14b624e781e492d92deacbf";

    /**
     * DES加密后再base64加密
     *
     * @param data
     * @return
     */
    public static String Base64DESEncrypt(String data) {
        return Base64.encode(DESUtil.DESEncrypt(data));
    }

    /**
     * 先base64解密再DES解密
     *
     * @param byteDESData
     * @return
     */
    public static String Base64DESDecrypt(String byteDESData) {
        return DESUtil.DESDecrypt(Base64.decode(byteDESData));
    }

    /**
     * DES加密
     *
     * @param data
     * @return
     */
    public static byte[] DESEncrypt(String data) {
        DES des = SecureUtil.des(DES_KEY.getBytes());
        return des.encrypt(data);
    }


    /**
     * DES解密
     *
     * @param secureData
     * @return
     */
    public static String DESDecrypt(byte[] secureData) {
        DES des = SecureUtil.des(DES_KEY.getBytes());
        try {
            return new String(des.decrypt(secureData), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据密钥种子生成密钥
     *
     * @return
     */
    public static String generateKey() {
        return SecureUtil.md5(DES_KEY_SEED);
    }


    public static void main(String[] args) {
        System.out.println("加密密钥:" + DESUtil.generateKey());
        String data = "你好，世界，Java,31415926";
        System.out.println("DES加密前:" + data);
        byte[] byteDESData = DESUtil.DESEncrypt(data);
        System.out.println("DES加密后:" + byteDESData.toString());
        String base64DESData = Base64.encode(byteDESData);
        System.out.println("DES加密再转base64后:" + base64DESData);

        byteDESData = Base64.decode(base64DESData);
        System.out.println("base64解密:" + byteDESData);
        data = DESUtil.DESDecrypt(byteDESData);
        System.out.println("DES解密后:" + data);


        base64DESData = DESUtil.Base64DESEncrypt(data);
        System.out.println("DES加密再Base64加密:" + base64DESData);

        data = DESUtil.Base64DESDecrypt(base64DESData);
        System.out.println("Base64解密再DES解密:" + data);
    }

}
